import utils.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author ZhangCuirong
 * @Date 2025/9/5 9:25
 * @description:
 */
public class Solution113 {
    List<List<Integer>> res;

    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        res = new LinkedList<>();
        if (root == null) {
            return res;
        }
        backtrack(root, targetSum, new LinkedList<>());
        return res;
    }

    public void backtrack(TreeNode root, int targetSum, LinkedList<Integer> path) {
        path.add(root.val);
        targetSum -= root.val;
        if (root.left == null && root.right == null) {
            if (targetSum == 0) {
                res.add(new ArrayList<>(path));
            }
        }
        if (root.left != null) {
            backtrack(root.left, targetSum, path);
        }
        if (root.right != null) {
            backtrack(root.right, targetSum, path);
        }
        path.removeLast();
    }

    public static void main(String[] args) {
        Solution113 solution = new Solution113();
        TreeNode root = TreeNode.buildTree(new int[]{5, 4, 8, 11, -1, 13, 4, 7, 2, -1, -1, 5, 1}, -1);
        System.out.println(solution.pathSum(root, 22));
    }
}
